<template>
  <div class="selectBox">
    <el-radio :label="label">{{ label }}</el-radio>
    <!-- 使用了sync所以$emit第一个参数必须是upadte -->
    <el-input :value="text" @input="$emit('update:text', $event)"></el-input>
    <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="image" :src="baseUrl + '/' + image" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'singleOption',
  props: ['label', 'text', 'image'],
  data () {
    return {
      // 上传给服务器的 Url
      uploadUrl: process.env.VUE_APP_BaseURL + '/question/upload',
      //  基础地址
      baseUrl: process.env.VUE_APP_BaseURL
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      // console.log('res:', res)
      console.log('file', file)
      this.$emit('update:image', res.data.url)
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less">
.singleSelect {
  .selectBox {
    margin-bottom: 45px;
  }
  .el-radio-group {
    width: 100%;
    .selectBox {
      display: flex;
      align-items: center;
      .avatar-uploader {
        margin-left: 20px;
      }
    }
  }
}
</style>
